<?php

namespace addons\shopro\controller\second;

use think\Db;
use think\Config;
use app\common\exception\UploadException;
use app\common\library\Upload;
use addons\shopro\controller\Common;
use app\admin\model\shopro\third\Letters as LettersModel;
use app\admin\model\shopro\order\Sign as SignModel;

class Letter extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    protected $curPath = "";

    // 签名保存的图片地址
    private $signDir = '/uploads/sign/';

    /**
     * 同意书详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $letter = LettersModel::where('id', $id)->find();
        if (!$letter) {
            $this->error(__('No Results were found'));
        }

        $this->success('获取成功', $letter);
    }

    public function getUniqId()
    {
        $user = auth_user(); 
        $result = [];
        $result['uniq_id'] = uniqid();
        $this->success('获取成功', $result);
    }

    // 临时保存签名 
    public function saveSign()
    {
        $user = auth_user();
        /*
        $params = $this->request->param();
        if (empty($params['uniq_id']) || empty($params['sign'])) {
            $this->error('缺少必要参数');
        }

        $filePath = $this->saveImage($params['uniq_id'], $params['sign']);
        // 插入记录
        $data['user_id'] = $user->id;
        $data['uniq_id'] = $params['uniq_id'];
        $data['image'] = $filePath;

        $signModel = new SignModel();
        $signModel->save($data);
    
        $this->success('保存成功');
        */

        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');

        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        $params = $this->request->post();
        if (empty($params['uniq_id'])) {
            $this->error('缺少必要参数');
        }

        $curPath = ROOT_PATH . "public";

        $subDir = $this->signDir . date('Ymd');
        $destDir = $curPath . $subDir;
        $this->createDir($destDir);
        $filePath = $subDir . '/' . $params['uniq_id'] . '.jpg';
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload($filePath);
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }
        // 插入记录
        $data['user_id'] = $user->id;
        $data['uniq_id'] = $params['uniq_id'];
        $data['image'] = $attachment->url;

        $signModel = new SignModel();
        $signModel->save($data);

        $this->success('ok', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }

    private function saveImage($uniqId, $signStr)
    {
        //匹配出图片的信息
        $match = preg_match('/^(data:\s*image\/(\w+);base64,)/', $signStr, $result);
        if(!$match){
            $this->error('签名图片格式不对');
        }
        $base64Image = str_replace($result[1], '', $signStr);
        $fileContent = base64_decode($base64Image);
        $this->curPath = ROOT_PATH . "public";

        $filePath = "";
        if (!empty($signStr)) {
            $subDir = $this->signDir . date('Ymd');
            $destDir = $this->curPath . $subDir;
            $this->createDir($destDir);
            $filePath = $subDir . '/' . $uniqId . '.jpg';
            $imgFile = $this->curPath . $filePath;
            file_put_contents($imgFile, $fileContent);
        }

        return $filePath;

    }

    private function createDir($destDir)
    {
        if (!is_dir($destDir)) {
            @mkdir($destDir, 0755, true);
        }
    }

}
